﻿/* 
 * This file is part of the Coffee Survey Framework - http://coffee.codeplex.com
 */
using System.Web.UI.WebControls;
using System.Xml;
using Coffee.ServiceLocators;

namespace Coffee
{
    public class Binding
    {

        public static void ConfigureBinding(DataBoundControl control, XmlNode config)
        {
            XmlNode data = config.SelectSingleNode("data");
            if (data != null)
            {
                XmlNode src = data.SelectSingleNode("src");
                string type = src.Attributes["type"].Value;
                BindingDelegate binder = BindingService.ResolveProvider(type);
                if (binder != null)
                    binder(control, src);
            }
        }

        public static void Map(object target, XmlNode node, string path)
        {
            XmlNodeList mappings = null;
            XmlNode quesnode = node.ParentNode.ParentNode;
            if ((quesnode.Name == "question") && ((quesnode.Attributes["type"].Value == "DropDownList") || (quesnode.Attributes["type"].Value == "RadioButtonList")) && (node.SelectNodes(path).Count == 0))
            {
                XmlDocument defaultMapping = new XmlDocument();
                defaultMapping.LoadXml("<mapping><map property=\"DataTextField\"><value>Text</value></map><map property=\"DataValueField\"><value>Value</value></map></mapping>");
                mappings = defaultMapping.SelectNodes("mapping/map");
            }
            else
            {
                mappings = node.SelectNodes(path);
            }

            if ((mappings != null) && (mappings.Count > 0))
            {
                foreach (XmlNode map in mappings)
                {
                    if (target.GetType() == typeof(System.Web.SessionState.HttpSessionState))
                    {
                        ((System.Web.SessionState.HttpSessionState)target)[map.Attributes["property"].Value] = Parser.ParseValue(map.SelectSingleNode("value"));
                    }
                    else
                    {
                        if (map.Attributes["index"] != null)
                        {
                            Reflection.SetProperty(map.Attributes["property"].Value, target, map.Attributes["index"].Value, Parser.ParseValue(map.SelectSingleNode("value")));
                        }
                        else
                        {
                            Reflection.SetProperty(map.Attributes["property"].Value, target, Parser.ParseValue(map.SelectSingleNode("value")));
                        }
                    }
                }
            }
        }

        public static void Map(object target, XmlNode node)
        {
            Map(target, node, "mapping/map");
        }

    }
}
